import {Ref, ref, UnwrapRef} from "vue";
import {RegisterUser, RegisterRules} from "@/common/interface/register.ts";

//密码匹配
const validatePass2 = (rule: RegisterRules, value: string, callback: any) => {
    if (value === '') {
        callback(new Error('请再次输入密码'))
    } else if (value !== registerUser.value.password) {
        callback(new Error("两次输入的密码不一致"))
    } else {
        callback()
    }
}

//手机号格式校验
const validatePhone = (rule: RegisterRules, value: string, callback: any) => {
    const reg = /^1[3456789][0-9]{9}$/
    if (!reg.test(value)) {
        callback(new Error("手机号码格式不正确"))
    } else {
        callback()
    }
}

// 注册用户
export const registerUser: Ref<UnwrapRef<RegisterUser>> = ref<RegisterUser>({
    nickName: "",
    userName: "",
    password: "",
    password2: "",
    phone: "",
    sex: "0",
    role: ""
})

//表单校验
export const registerRules: Ref<UnwrapRef<RegisterRules>> = ref<RegisterRules>({
    nickName: [
        {required: true, message: '姓名不能为空', trigger: 'blur'},
        {min: 2, max: 30, message: '姓名为2~30个字符', trigger: 'blur'}
    ],
    userName: [{required: true, message: '账号不能为空', trigger: 'blur'}],
    password: [
        {required: true, message: '密码不能为空', trigger: 'blur'},
        {min: 6, max: 30, message: '密码长度为6~30个字符', trigger: 'blur'}
    ],
    password2: [
        {required: true, message: '确认密码不能为空', trigger: 'blur'},
        {min: 6, max: 30, message: '密码长度为6~30个字符', trigger: 'blur'},
        {validator: validatePass2, trigger: 'blur'}
    ],
    phone: [
        {required: true, message: '手机号码不能为空', trigger: 'blur'},
        {validator: validatePhone, trigger: 'blur'}
    ]
})